//
//  QRCodeViewController.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/15.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit

import AVFoundation

class QRCodeViewController: UIViewController {
    ///二维码内容视图
    @IBOutlet weak var qrCodeContanerView: UIView!
    
    ///底部tabbar控制条
    @IBOutlet weak var QRTabBar: UITabBar!
    ///扫描二维码内容
    @IBOutlet weak var qrCodeLable: UILabel!
    
    ///容器试图的高度
    @IBOutlet weak var containerViewHeright: NSLayoutConstraint!
    ///二维码顶部的约束
    @IBOutlet weak var qrCodeImageViewTop: NSLayoutConstraint!
    ///扫描动画 视图
    @IBOutlet weak var qrCodeImageView: UIImageView!
    
    //MARK:- view生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        QRTabBar.selectedItem = QRTabBar.items?.first
        QRTabBar.backgroundImage = #imageLiteral(resourceName: "qrcode_tabbar_background")
        
        //底部控制条设置代理监
        QRTabBar.delegate =  self
        
        //扫描二维码
        scanQRCode()
        
        //添加二维码外框容器Layer
        view.layer.addSublayer(qrCodeContainLayer)
    }
    
    //在view完全显示的时候做动画
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //开始扫描动画
        qrCodeAnimationStart()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //修改约束
        qrCodeImageViewTop.constant = -containerViewHeright.constant
        view.layoutIfNeeded()
    }

    //MARK:- 内部控制方法
    ///扫描二维码
    private func scanQRCode(){
        //判断输入输出能否加入session
        if !qrCodeSession.canAddInput(qrCodeInput!){
            ZHLog("输入设备不能使用")
            return
        }
        if !qrCodeSession.canAddOutput(qrCodeOutput){
            return
        }
        //输入输出加入会话
        qrCodeSession.addInput(qrCodeInput!)
        qrCodeSession.addOutput(qrCodeOutput)
        
        //设置输出的样式
        qrCodeOutput.metadataObjectTypes = qrCodeOutput.availableMetadataObjectTypes
        
        //设置监听 代理和队列
        qrCodeOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        
        //添加预览图层
        view.layer.insertSublayer(arCodeReviewLayer, at: 0)
        //开始扫描
        qrCodeSession.startRunning()
    }
    
    ///扫描二维码动画
    private func qrCodeAnimationStart(){
        //修改约束
        qrCodeImageViewTop.constant = -containerViewHeright.constant
        view.layoutIfNeeded()
        //二维码扫描动画
        UIView.animate(withDuration: 1.5) {
            //动画次数无限
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.qrCodeImageViewTop.constant = self.containerViewHeright.constant
            //修改约束后调用
            self.view.layoutIfNeeded()
        }
    }
    
    ///相册按钮点击
    @IBAction func photoBtnClick(_ sender: Any) {
        //打开相册
        //判断相册可以打开吗
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
            return
        }
        let photoVC = UIImagePickerController()
        
        photoVC.delegate = self
        //弹出相册
        present(photoVC, animated: true, completion: nil)
    }
    
    ///关闭按钮点击
    @IBAction func closeBtnClick(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    //MARK:- 懒加载
    ///输入设备
    private lazy var qrCodeInput: AVCaptureDeviceInput? = {
        
        let device = AVCaptureDevice.default(for: AVMediaType.video)
        return try? AVCaptureDeviceInput(device: device!)
    }()
    
    ///会话
    private lazy var qrCodeSession: AVCaptureSession = AVCaptureSession()
    
    ///输出
    private lazy var qrCodeOutput: AVCaptureMetadataOutput = {
        let output = AVCaptureMetadataOutput()
        //计算扫描区域
        let containerFrame = qrCodeContanerView.frame
        let viewFrame = self.view.frame
        let x = containerFrame.origin.y / viewFrame.height
        let y = containerFrame.origin.x / viewFrame.width
        let width = containerFrame.height / viewFrame.height
        let height = containerFrame.width / viewFrame.width
        output.rectOfInterest = CGRect(x: x, y: y, width: width, height: height)
        return output
    }()
    
    ///预览图层
    private lazy var arCodeReviewLayer: AVCaptureVideoPreviewLayer = {
        let layer =  AVCaptureVideoPreviewLayer(session: self.qrCodeSession)
        layer.frame = self.view.bounds
        return layer
    }()
    
    ///二维码外框的容器Layer
    private lazy var qrCodeContainLayer = { () -> CALayer in
        let layer = CALayer()
        layer.frame = self.view.bounds
        return layer
    }()
}

//MARK:- UITabBarDelegate
extension QRCodeViewController: UITabBarDelegate{
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        //根据按钮选择对应尺寸
        item.tag == 0 ? (containerViewHeright.constant = 300) : (containerViewHeright.constant = 150)
        
        //关闭动画
        qrCodeImageView.layer.removeAllAnimations()
        
        //开始动画
        qrCodeAnimationStart()
        
    }
}

//MARK:- AVCaptureMetadataOutputObjectsDelegate
extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate{
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        
        //清除上一次的layer
        removeSubLayers()
        
        guard let metadata = metadataObjects.last else {
            return
        }
        //复制二维码内容
        qrCodeLable.text = (metadata as? AVMetadataMachineReadableCodeObject)?.stringValue
        
        //画二维码外框
        drawQRCodeLines(obj: arCodeReviewLayer.transformedMetadataObject(for: metadata) as? AVMetadataMachineReadableCodeObject)
    }
    
    ///清除二维码 外框容器layer中所有子layer
    private func removeSubLayers(){
        guard let layers = qrCodeContainLayer.sublayers else {
            return
        }
        for layer in layers{
            layer.removeFromSuperlayer()
        }
    }
    
    ///画二维码的外框
    private func drawQRCodeLines(obj: AVMetadataMachineReadableCodeObject?){
        guard let codeObj = obj else{
            return
        }
        
        //创建图层 设置属性
        let layer = CAShapeLayer()
        layer.lineWidth = 1
        layer.strokeColor = UIColor.green.cgColor
        layer.fillColor = UIColor.clear.cgColor
        
        //创建路径
        let path = UIBezierPath()
        //移动到起点
        path.move(to: codeObj.corners[0])
        //移动到其它点
        let count = codeObj.corners.count
        for point in codeObj.corners[1..<count]{
        path.addLine(to: point)
        }
        //关闭路径
        path.close()
        //设置路径
        layer.path = path.cgPath
        
        qrCodeContainLayer.addSublayer(layer)
        
    }
}

//MARK:- UIImagePickerControllerDelegate & UINavigationControllerDelegate
extension QRCodeViewController: UIImagePickerControllerDelegate & UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    
        //取出照片
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else{
            return
        }
        //创建识别器
        guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyLow]) else {
            return
        }
        
        guard let ciImage = CIImage(image: image) else {
            return
        }
        let features = detector.features(in: ciImage)
        
        for feature in features{
            let meassage = feature as! CIQRCodeFeature
            ZHLog (meassage.messageString)
        }
        
        //隐藏相册控制器
        picker.dismiss(animated: true, completion: nil)
    }
}
